package com.example.id;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.domain.ID;
@Service
public class IdGeneratorDao {

	@PersistenceContext
	EntityManager entityManager;
	
	@Transactional
	public Long get(SeqEnum seq,int count){
		ID Id=entityManager.find(ID.class,seq.id,LockModeType.PESSIMISTIC_WRITE);
		Long returnValue = 0L;
		Long nextValue = 0L;
		int add=count;
		if(add<=0){
			add=1;
		}
		if(Id==null){
			returnValue=1l;
			nextValue += add;
			Id=new ID();
			Id.setId(seq.id);
			Id.setSeqid(nextValue);
			Id.setSequeueName(seq.name);
			entityManager.persist(Id);
		}else{
			returnValue=Id.getSeqid()+1;
			nextValue =Id.getSeqid()+ add;
			Id.setSeqid(nextValue);
			entityManager.merge(Id);
			entityManager.flush();
		}
		
		return returnValue;
	}
	
	public Long getget(SeqEnum seq){
		return get(seq, 1);
	}

	

}
